<?php
/**
 * Author: Jesse
 * Email : jessedev@163.com
 * Date: 2024/6/18 10:21
 * FileName: HttpExceptionHandler.php
 * DESC: The Relentless Pursuit of Perfection.
 */

namespace Common\Kernel\Exception\Handler;

use Common\Constants\ErrorCode;
use Common\Constants\ResponseCode;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\MessageInterface;
use Throwable;

/**
 * Http异常处理器
 */
class HttpExceptionHandler extends ExceptionHandler
{
    #[Inject]
    protected FormatterInterface $formatter;

    #[Inject]
    protected ResponseInterface $response;

    /**
     * 处理异常类
     *
     * @param Throwable $throwable
     * @param \Psr\Http\Message\ResponseInterface $response
     * @return MessageInterface|ResponseInterface
     */
    public function handle(Throwable $throwable, \Psr\Http\Message\ResponseInterface $response): MessageInterface|ResponseInterface
    {
        // 控制台记录
        console_log()->debug(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        console_log()->debug($throwable->getTraceAsString());

        // 文件日志记录
        logger()->warning('Http Exception Handler', ['exception' => $this->formatter->format($throwable)]);

        // 阻止异常冒泡
        $this->stopPropagation();

        // 将错误响应
        return $this->response->withStatus(ErrorCode::SERVER_ERROR)->errorJson($throwable->getCode() ?: ResponseCode::ERROR, $throwable->getMessage());
    }

    /**
     * 是否校验
     *
     * @param Throwable $throwable
     * @return bool
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}